import { Article } from '@/types/data'
import { ArticleAction } from '@/types/store'

type State = {
  [key: string]: {
    timestamp: string
    articles: Article[]
  }
}

const channelArticles: State = {
  1: {
    timestamp: '1638408103353',
    articles: []
  }
}

export default function article (
  state = channelArticles,
  action: ArticleAction
): State {
  if (action.type === 'article/getArticles') {
    console.log(action.payload, 456789132)
    const { channelId, timestamp, articles } = action.payload
    let old: Article[] = []
    if (state[channelId]) {
      old = state[channelId].articles
    }
    return {
      ...state,
      [channelId]: {
        timestamp,
        articles: [...old, ...articles]
      }
    }
  } else if (action.type === 'article/getNewArticles') {
    console.log(action.payload, 456789132)
    const { channelId, timestamp, articles } = action.payload
    let old: Article[] = []
    if (state[channelId]) {
      old = state[channelId].articles
    }
    return {
      ...state,
      [channelId]: {
        timestamp,
        articles: [...articles, ...old]
      }
    }
  }
  return state
}
